package com.guava.mall.tool.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.guava.mall.tool.common.exception.ServerException;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Optional;

/**
 * @Description:
 * @Auth: DengYunHu
 * @Date: 2021/3/31 17:03
 */
@Slf4j
public class ImageProvider {

    private static int fontSize = 30;//字体大小
    private static int background_left_side = 30;//红色边框左边距
    private static int background_bottom_side = 30;//红色边框底部边距
    private static int background_rounded_radius=25;//红色边框圆角半角

    private static int font_top_bottom_margin = 3;// 文字上下边距  （单边）
    private static int font_left_right_margin = 10;//文字左右边距 (单边)



    public static void main(String[] args) throws FileNotFoundException {
        String path = "D:\\图片\\test.jpg";
        String outPath = "D:\\图片\\test_out_2.png";
        addLayer(path, "NT$1891", outPath);
        System.out.println("执行完毕");
    }

    public static void addLayer(String sourcePath, String text, String outputPath) {
        OutputStream outputStream = null;
        InputStream inputStream=null;
        try {
            String markInfo = Optional.ofNullable(text).orElse("").trim();
            if (!markInfo.startsWith("NT$")){
                text="NT$".concat(markInfo);
            }
            inputStream=new FileInputStream(new File(sourcePath));
            Image img = ImageIO.read(inputStream);
            int width = ((BufferedImage) img).getWidth();
            int height = ((BufferedImage) img).getHeight();
            BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //图形，通过操作这个图形最终生成我们的图片
            Graphics2D graphics = bimage.createGraphics();

            // 消除文字锯齿
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.drawImage(img, 0, 0, null);//原图片作为底图

            //设置字体,加粗,大小
            Font font = new Font("微软雅黑", Font.BOLD, fontSize); //字体
            graphics.setFont(font);
            //获取字体 长和宽
            FontMetrics fm = graphics.getFontMetrics();
            int fontWidth = fm.stringWidth(text);
            int fontHeight = fm.getHeight();
            System.out.println("fontWidth=" + fontWidth + " fontHeight=" + fontHeight);
//
//            // 1.设置长方形水印
            int backgroundWidth = fontWidth + font_left_right_margin * 2;//字符串背景填充块宽度 = 字体宽度+ 字体左右边距 （单边*2）
            int backgroundHeight = fontHeight + font_top_bottom_margin * 2;//红色边框高度= 字体高度 + 字体上下边距(单边*2)

            int backgroundX = background_left_side;//红色边框X坐标
            int backgroundY = height - backgroundHeight - background_bottom_side;//红色边框Y坐标= 原图高度- 红色边框高度 -底部边距

            Image backImage = loadBackground(backgroundWidth, backgroundHeight);
            graphics.drawImage(backImage, backgroundX, backgroundY, null);


            // 2.在长方形水印上方添加文字
            //设置底色
            graphics.setBackground(Color.white);

            int fontX = backgroundX + font_left_right_margin;// 字体X坐标 = 红色背景块的X坐标 + 字体左边距
            int fontY = backgroundY + fontHeight - font_top_bottom_margin * 2+1; // 字体X坐标 = 红色背景块的Y坐标 +字体高度 - 上下边距 *2 +1(向下便宜1个单位)


            System.out.println("backgroundX=" + backgroundX + "  backgroundY=" + backgroundY + " fontX=" + fontX + " fontY=" + fontY + "  backgroundWidth=" + backgroundWidth + "  backgroundHeight=" + backgroundHeight);

            graphics.drawString(text, fontX, fontY);


            graphics.dispose();
            graphics.dispose();
            // 3.往输出流中写数据
            outputStream = new FileOutputStream(new File(outputPath));
            ImageIO.write(bimage, FileUtil.extName(sourcePath), outputStream);

        } catch (Exception e) {
            log.error("convert error",e);
            throw new ServerException("转换异常");
        } finally {
            IoUtil.close(inputStream);
            IoUtil.close(outputStream);
        }
    }


    public static Image loadBackground(int backgroundWidth, int backgroundHeight) {
        BufferedImage bufferedImage = new BufferedImage(backgroundWidth, backgroundHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = bufferedImage.createGraphics();
        //graphics.clearRect(0, 0, backgroundWidth, backgroundHeight); 加上会出现黑色边框
        // 消除文字锯齿
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.setBackground(Color.white);
        graphics.setPaint(Color.red);
        graphics.fillRoundRect(0, 0, backgroundWidth, backgroundHeight, background_rounded_radius, background_rounded_radius);
        graphics.dispose();
        return bufferedImage;
    }
}
